'use strict';

/**
 * @description 接口访问次数插件
 * @author Bluer_Dai
 * */

/**
 * @param {Object} options 在某个时间端允许访问接口的最大次数
 */
module.exports = options => {
  let count = 0;
  let firstTime = new Date().getTime();

  return async (ctx, next) => {
    if (new Date().getTime() - firstTime >= options.time) {
      if (count >= options.maxCount) {
        count = 0;
        firstTime = new Date().getTime();
        ctx.body = {
          status: 500,
          message: '请求太频繁',
        };
        return;
      }
      count = 0;
      firstTime = new Date().getTime();
      await next();

    } else {
      count++;
      await next();
    }
  };
};
